package com.zoespeer.food_delivery_comment_api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zoespeer.food_delivery_comment_api.entity.UserFavorites;
import com.zoespeer.food_delivery_comment_api.mapper.FavoriteMapper;
import com.zoespeer.food_delivery_comment_api.service.FavoriteService;
import com.zoespeer.food_delivery_comment_api.vo.AddFavoriteVO;
import com.zoespeer.food_delivery_comment_api.vo.CancelLikeRequestVO;
import com.zoespeer.food_delivery_comment_api.vo.FavoriteVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Override
    public List<FavoriteVO> getMyLike(String userId) {
        if (userId == null || userId.trim().isEmpty()) {
            throw new RuntimeException("用户ID不能为空");
        }
        return favoriteMapper.selectMyLike(userId);
    }
    // 新增：取消收藏实现
    @Override
    public void cancelLike(CancelLikeRequestVO request) {
        // 1. 从VO获取String类型参数
        String userIdStr = request.getUserId();
        String canteenIdStr = request.getCanteenId();

        // 2. 非空校验
        if (userIdStr == null || userIdStr.trim().isEmpty() ||
                canteenIdStr == null || canteenIdStr.trim().isEmpty()) {
            throw new RuntimeException("userId和canteenId不能为空");
        }

        // 3. 将String类型参数转换为Integer（适配Entity层）
        Integer userIdInt;
        Integer canteenIdInt;
        try {
            userIdInt = Integer.parseInt(userIdStr);
            canteenIdInt = Integer.parseInt(canteenIdStr);
        } catch (NumberFormatException e) {
            throw new RuntimeException("用户ID/食堂ID格式错误，需为数字");
        }

        // 4. 查询用户是否收藏该餐厅（使用Integer类型参数匹配Entity）
        QueryWrapper<UserFavorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userIdInt) // 直接用Integer类型，匹配Entity字段
                .eq("restaurant_id", canteenIdInt); // canteenId对应数据库restaurant_id

        UserFavorites favorite = favoriteMapper.selectOne(queryWrapper);
        if (favorite == null) {
            throw new RuntimeException("未找到该用户对该餐厅的收藏记录，无需取消");
        }

        // 5. 执行删除（按收藏记录ID删除，避免多删）
        int rows = favoriteMapper.deleteById(favorite.getFavoriteId());
        if (rows <= 0) {
            throw new RuntimeException("取消收藏失败，请重试");
        }
    }
    // 新增方法：添加收藏餐厅
    @Override
    @Transactional
    public void addLike(AddFavoriteVO request) {
        // 1. 获取前端参数
        String userId = request.getUserId();
        String canteenIdStr = request.getCanteenId();

        // 2. 校验参数
        if (userId == null || userId.trim().isEmpty()) {
            throw new RuntimeException("用户ID不能为空");
        }
        if (canteenIdStr == null || !canteenIdStr.matches("\\d+")) {
            throw new RuntimeException("餐厅ID必须是数字");
        }
        Integer canteenId = Integer.parseInt(canteenIdStr);

        // 3. 检查是否已收藏
        QueryWrapper<UserFavorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("restaurant_id", canteenId);
        if (favoriteMapper.exists(queryWrapper)) {
            throw new RuntimeException("该餐厅已被收藏，无需重复操作");
        }

        // 4. 新增收藏记录
        UserFavorites favorite = new UserFavorites();
        favorite.setUserId(userId);
        favorite.setRestaurantId(canteenId); // 前端canteenId映射为数据库restaurant_id
        favorite.setCreatedAt(LocalDateTime.now());

        int rows = favoriteMapper.insert(favorite);
        if (rows <= 0) {
            throw new RuntimeException("收藏餐厅失败，请重试");
        }
    }
}